package com.itheima.day05.shop.dao;

import com.itheima.day05.shop.pojo.Product;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ProductRepository {
    private final static   URL resource = ProductRepository.class.getClassLoader().getResource("products.txt");
    public List<Product> findAll() {
        try {
            List<String> lines = FileUtils.readLines(new File(resource.toURI()));
           return  lines.stream().map(line -> {
                String[] strings = line.split(",");
               String id=strings[0];
               if(id == null || "".equals(id)){
                   id=System.currentTimeMillis()+"";
               }
                Product product = new Product(Long.parseLong(id),strings[1],Double.parseDouble(strings[2]),Long.parseLong(strings[3]));
                return product;
            }).toList();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Product>();
        }
    }
    public Product findById(Long id) {
        List<Product> products = findAll();
        for (Product product : products) {
            if(product.getId().equals(id)){
                return product;
            }
        }
        return null;
    }
    public void save(Product product) {
        try {
            String id=System.currentTimeMillis()+"";
            String content =id +","+product.getName()+","+product.getPrice()+","+product.getStockQuantity();
            FileUtils.writeLines(new File(resource.toURI()), Arrays.asList(content),true);
            System.out.println("保存数据:............"+content);
        } catch (Exception e) {
            System.out.println("报错了..........");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public void deleteById(Long id) {
        try {
            List<Product> products = findAll();
            List<String> lines = products.stream().filter(p -> !p.getId().equals(id)).map(
                    product -> {
                        String content = product.getId() + "," + product.getName() + "," + product.getPrice() + "," + product.getStockQuantity();
                        return content;
                    }
            ).toList();

            FileUtils.writeLines(new File(resource.toURI()),lines);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}